const toPromise = require("./to-promise")
const regeneratorRuntime = require("../vendor/regenerator-runtime")
const co = require("../vendor/co")
const loginUrl = "login/index"
const maxRetry = 3
let retry = 0
let cache = {};//在用户拒绝授权后，保存当前请求信息，用于下次请求
let baseUrl = "https://xcx.ec51.com/v1/";//请求根地址
// let baseUrl ='http://ec51.xcx.com/v1/'

function wxLogin() {
    return new Promise((resolve, reject) => {
        console.log('【wx.login】')
        wx.login({
            success: function (res) {
                console.log('【wx.login】success')
                resolve(res)
            },
            fail: function () {
                console.warn("【wx.login】fail")
                reject(false)
            }
        })
    })
}

function wxGetUserInfo() {
    return new Promise((resolve, reject) => {
        wx.getUserInfo({
            success: res => {
                wx.setStorage({
                    key: 'user',
                    data: res.userInfo
                })
                resolve(res)
            },
            fail: err => {
                reject(err)
            }
        })
    })
}


function wxRequest(url, method = "GET", data = {}, header = {}) {
    return new Promise((resolve, reject) => {
        wx.request({
            url,
            data,
            method,
            header,
            success: res => {
                const code = res.data.status.code
                if (code === 2000) {
                    resolve(res.data)
                } else {
                    reject(res.data.status)


                }
            },
            fail: err => {
                reject(err)
            }
        })
    })
}


function checkSession() {
    return new Promise((resolve, reject) => {
        wx.checkSession({
            success: () => {
                resolve()
            },
            fail: () => {
                reject()
            }
        })
    })
}

function doRequest(url, config = {}) {
    const localConfig = Object.assign({
        method: "GET",
        data: {},
        showMsg: false,
        showLoading: false
    }, config)
    const rawUrl = baseUrl + url
    return co(function* () {
        let sid = wx.getStorageSync("sid")
        const storeId = getApp().storeId
        if (!storeId) {
            throw new ReferenceError("请在app.js里设置storeId")
        }
        try {
            yield checkSession()
            if (!sid) {
                throw "sid-error"
            }
        } catch (err) {

            const loginInfo = yield wxLogin()
            const loginRes = yield wxRequest(baseUrl + loginUrl, "GET", {}, {
                'Code': loginInfo.code,
                'store-id': storeId,
            })
            sid = loginRes.data.sid
            wx.setStorage({
                key: 'sid',
                data: loginRes.data.sid
            })
            wx.setStorage({
                key: 'mid',
                data: loginRes.data.member_id
            })
            wx.setStorage({
                key: 'store',
                data: loginRes.data.store_name
            })
        }
        try {
            localConfig.showLoading === true && wx.showLoading({
                title: '加载中...',
            })
            const r = yield wxRequest(rawUrl, localConfig.method, localConfig.data, { sid, "store-id": storeId })
            retry = 0
            console.log(r)
            wx.hideLoading()
            return r
        } catch (err) {
            wx.hideLoading()
            console.log(err)
            if (err.code === 40001) {
                if (retry < maxRetry) {
                    retry++
                    wx.removeStorageSync("sid")
                    return doRequest(url, localConfig)
                }
            }
            localConfig.showMsg === true && getApp().wxToast.error(err.message)
            throw err

        }
    })
}


module.exports = {
    get: (url, config = {}) => {
        config.method = "GET";
        return doRequest(url, config)
    },
    post: (url, config = {}) => {
        config.method = "POST";
        return doRequest(url, config)
    }
}
